package org.testile.placeholderscript;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.script.ScriptEngine;

/**
 * A skeletal implementation of the {@link PlaceholderTransformer} using {@link Pattern}s
 * to determine suitability of the String value to be transformed.
 *
 * @author hvizmar
 */
public abstract class AbstractPatternTransformer implements PlaceholderTransformer {

	protected final Pattern pattern;
	protected ScriptEngine  engine;

	public AbstractPatternTransformer(Pattern pattern) {
		this.pattern = pattern;
	}

	/**
	 * Transforms a string value matching the defined pattern to the resulting
	 * transformed string.
	 *
	 * @param match a match result of a matching string
	 * @return the transformed string
	 */
	protected abstract String transformMatch(MatchResult match);

	public final boolean isSuitable(String value) {
		Matcher match = pattern.matcher(value);
		return match.matches();
	}

	public final String transform(String matchingPattern) {
		Matcher match = pattern.matcher(matchingPattern);

		if(match.matches()) {
			return transformMatch(match.toMatchResult());
		}

		throw new IllegalArgumentException("String [" + matchingPattern + "] does not match pattern [" + pattern + "].");
	}

	public void registerScriptEngine(ScriptEngine engine) {
		this.engine = engine;
	}
}
